import axios from 'axios';
import { gotoLogin } from '../request';
import sessionStorage from './storage'
import $message from '../components/Message'
import * as util from './util'
import config from '@/config'
import instance from "@/utils/http";
import store from "@/store";

const

  toLogin = () => {
    gotoLogin().then((res: any) => {
      sessionStorage.remove('token')
      location.href = `${res.data}&ReturnUrl=${location.href}`;
    });
  }

const service: any = axios.create({
  baseURL: config.baseURL,
  withCredentials: false,
  timeout: 120000 // request timeout
})
// service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

console.log(config.baseURL)
var requestOptions = ['Post', 'Delete', 'Put', 'Patch'];
//设置请求头
service.interceptors.request.use(
  (settings: any) => {
    // if (!settings.headers["X-Request-With"]) {
    //   settings.headers["X-Request-With"] = 'XMLHttpRequest';
    // }
    if (settings.url.indexOf("login") == -1) {
      var token = sessionStorage.get('token');


      token && (settings.headers.common['X-Token']  = token);
      // if (token) {
      //   settings.headers.Authorization = "Bearer " + token;
      // }
    }

    return settings;
  },
  (error: any) => {
    console.log(error);
    return Promise.reject(error)
  }
)
//设置响应头
service.interceptors.response.use(
  (res: any) => {
    if (res.data == 401) {
      toLogin()
      return Promise.reject(res)
    } else if (res.status == 500) {
      $message.error('请求失败');
      return Promise.reject(res)
    } else {
      return Promise.resolve(res)
    }
    // return new Promise((resolve, reject) => {
    //   var success = res.status >= 200 && res.status < 300;
    //   if (success) {
    //     var data = res.data;
    //     if (typeof data.state === 'undefined' || data.state != 0) {
    //       resolve(data);
    //     } else {
    //       if (data.errorCode) {
    //         $message.error(data.message);
    //       }
    //       reject(data);
    //     }
    //   } else {
    //     $message.error('StatusCode: ' + res.status)

    //     reject(data);
    //   }
    // });
  },
  (err: any) => {
    console.log(err);
    var res = err.response;
    if (res.status == 403) {
      $message.error('You do not have permission to access')
    }
    else if (res.status == 401) {
      $message.error('Login is invalid, please refresh the page')
      toLogin();
    } else {
      $message.error('Application Server Exception')
    }
    return Promise.reject(err);
  }
)

requestOptions.forEach(function (option: any) {
  var o = option.toLowerCase();
  service['body' + option] = function (url: string, data: any, settings: any) {
    if (o === "delete") {
      data = {
        data: data
      };
      Object.assign(settings, data);
      return service[o](url, settings);
    }
    return service[o](url, data, settings);
  };

  service['form' + option] = function (url: string, data: any, settings: any) {
    if (!settings) settings = {};
    if (!settings.transformRequest || settings.transformRequest.length == 0) {
      settings.transformRequest = [];
    }
    settings.transformRequest.push(util.transformRequestQs);
    if (o === "delete") {
      data = {
        data: data,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      };
      Object.assign(settings, data);
      return service[o](url, settings);
    }
    return service[o](url, data, settings);
  };
});

service.orgGet = service.get;
service.get = function (url: string, data: any, settings: any) {
  if (data) {
    settings = settings || {};
    if (!data.params) {
      settings.params = data;
    } else {
      settings = data;
    }
  }
  return service.orgGet(url, settings);
};

export default service
